package com.ksyun.seckill.service;

import com.ksyun.common.util.collection.CollectionUtil;
import com.ksyun.seckill.constants.SecKillImplVer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ApplicationContextEvent;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 服务实现类路由.
 * @author ksc
 */
@Component
public class RouterService implements ApplicationListener<ApplicationContextEvent> {

    private Map<SecKillImplVer, SkService> skServiceMap;

    @Override
    public void onApplicationEvent(ApplicationContextEvent event) {
        ApplicationContext context = event.getApplicationContext();
        this.initSkServiceRouter(context);
    }

    public SkService getSkService(SecKillImplVer secKillImplVer) {
        return skServiceMap.get(secKillImplVer);
    }

    private void initSkServiceRouter(ApplicationContext context) {
        Map<String, SkService> beanMap = context.getBeansOfType(SkService.class);
        this.skServiceMap = CollectionUtil.newHashMapWithCapacity(beanMap.size(), 0.5f);
        for (SkService delayTaskExecService : beanMap.values()) {
            this.skServiceMap.put(delayTaskExecService.getSecKillImplVer(), delayTaskExecService);
        }
    }
}
